"""
Authentication utilities - compatible with YonYou styles.
"""
from functools import wraps
from flask import request
from app.services.auth_service import AuthService
from app.utils.response import error_response


def require_auth(f):
    """Authentication decorator.

    Rules:
    - Prefer header Authorization: Bearer <token>
    - Fallback to query param access_token (YonYou style)
    - Skip for certain endpoints (health, auth token shortcut)
    """

    @wraps(f)
    def decorated_function(*args, **kwargs):
        # Skip auth for health check and simple auth token endpoint
        if request.endpoint in ["health", "auth.get_auth_token"]:
            return f(*args, **kwargs)

        import logging

        # 1) Prefer Authorization header
        auth_header = request.headers.get("Authorization")
        token = None
        if auth_header and auth_header.startswith("Bearer "):
            token = auth_header.replace("Bearer ", "")
        else:
            # 2) YonYou compatibility: access_token in query string
            query_token = request.args.get("access_token")
            if query_token:
                token = query_token
                logging.info(
                    f"[Auth] Using access_token from query - endpoint: {request.endpoint}"
                )

        if not token:
            logging.warning(
                f"[Auth] Missing token (no Authorization header and no query access_token) - endpoint: {request.endpoint}"
            )
            return error_response("Missing Authorization header", code="401"), 401

        logging.info(
            f"[Auth] Validating token: {token[:20]}... (length: {len(token)}) - endpoint: {request.endpoint}"
        )

        # Validate token
        if not AuthService.validate_token(token):
            logging.warning(
                f"[Auth] Token validation failed: {token[:20]}... - endpoint: {request.endpoint}"
            )
            return error_response("Invalid or expired token", code="401"), 401

        logging.info(
            f"[Auth] Token validated successfully - endpoint: {request.endpoint}"
        )
        return f(*args, **kwargs)

    return decorated_function

